<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>五子棋游戏</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
        }

        #board {
            display: grid;
            grid-template-columns: repeat(19, 30px);
            grid-template-rows: repeat(19, 30px);
            gap: 0;
            border: 2px solid #333;
            background-color: #d8b595;
        }

        .cell {
            width: 30px;
            height: 30px;
            border: 1px solid #ccc;
            box-sizing: border-box;
            position: relative;
        }

        .stone {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            position: absolute;
            top: 1px;
            left: 1px;
        }

        .black {
            background-color: #000;
        }

        .white {
            background-color: #fff;
        }

        button {
            margin: 10px;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }

        #status {
            margin-top: 10px;
            font-size: 18px;
        }

        input[type="checkbox"] {
            margin-right: 5px;
        }
    </style>
</head>
<body>
<div id="board"></div>
<div>
    <label><input type="checkbox" id="aiCheckbox"> 对战AI</label>
    <button id="newGame">新游戏</button>
    <button id="saveGame">保存存档</button>
    <button id="loadGame">读取存档</button>
    <input type="text" id="username" placeholder="请输入用户名">
    <p id="status">当前玩家: 黑棋</p>
</div>

<script>
    const boardElement = document.getElementById('board');
    const newGameButton = document.getElementById('newGame');
    const aiCheckbox = document.getElementById('aiCheckbox');
    const statusText = document.getElementById('status');
    const saveGameButton = document.getElementById('saveGame');
    const loadGameButton = document.getElementById('loadGame');
    const usernameInput = document.getElementById('username');

    const BOARD_SIZE = 19;
    let currentPlayer = 1; // 1 表示黑棋，2 表示白棋

    // 绘制棋盘
    function drawBoard() {
        boardElement.innerHTML = '';
        for (let i = 0; i < BOARD_SIZE; i++) {
            for (let j = 0; j < BOARD_SIZE; j++) {
                const cell = document.createElement('div');
                cell.classList.add('cell');
                cell.dataset.row = i;
                cell.dataset.col = j;
                cell.addEventListener('click', handleCellClick);
                boardElement.appendChild(cell);
            }
        }
    }

    // 处理单元格点击事件
    async function handleCellClick(event) {
        const row = parseInt(event.target.dataset.row);
        const col = parseInt(event.target.dataset.col);

        if (!event.target.querySelector('.stone')) { // 只允许在空位落子
            try {
                await makeMove(row, col);
            } catch (error) {
                console.error('Error:', error);
            }
        }
    }

    // 发送移动请求到服务器
    async function makeMove(row, col) {
        const response = await fetch('/api/wuziqi/move', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ row, col })
        });
        const data = await response.json();

        if (data) {
            placeStone(row, col, currentPlayer);
            if (data.win) {
                statusText.textContent = `${currentPlayer === 1 ? '黑棋' : '白棋'} 获胜！`;
                disableBoard();
            } else if (data.draw) {
                statusText.textContent = '平局！';
            } else {
                if (aiCheckbox.checked) {
                    currentPlayer = 2; // 切换到白棋（AI）
                    statusText.textContent = '当前玩家: AI';
                    setTimeout(makeAIMove, 300); // 延迟让玩家看到自己的落子
                } else {
                    currentPlayer = currentPlayer === 1 ? 2 : 1; // 交替落子
                    statusText.textContent = `当前玩家: ${currentPlayer === 1 ? '黑棋' : '白棋'}`;
                }
            }
        }
    }

    // 放置棋子
    function placeStone(row, col, player) {
        const stone = document.createElement('div');
        stone.classList.add('stone', player === 1 ? 'black' : 'white');
        document.querySelector(`.cell[data-row="${row}"][data-col="${col}"]`).appendChild(stone);
    }

    // 请求AI下棋
    async function makeAIMove() {
        try {
            const response = await fetch('/api/wuziqi/ai-move', { method: 'GET' });
            const data = await response.json();
            const { row, col, win, draw } = data;

            placeStone(row, col, currentPlayer);
            if (win) {
                statusText.textContent = `AI 获胜！`;
                disableBoard();
            } else if (draw) {
                statusText.textContent = '平局！';
            } else {
                currentPlayer = 1; // 切换回玩家
                statusText.textContent = '当前玩家: 黑棋';
            }
        } catch (error) {
            console.error('Error:', error);
        }
    }

    // 开始新游戏，重置游戏状态
    async function resetGame() {
        try {
            await fetch('/api/wuziqi/new-game', { method: 'POST' });
            currentPlayer = 1;
            statusText.textContent = '当前玩家: 黑棋';
            drawBoard();
        } catch (error) {
            console.error('Error:', error);
        }
    }

    // 禁用棋盘，移除所有单元格的点击事件监听器
    function disableBoard() {
        const cells = document.querySelectorAll('.cell');
        cells.forEach(cell => cell.removeEventListener('click', handleCellClick));
    }

    // 保存游戏存档
    async function saveGame() {
        const username = usernameInput.value;
        if (!username) {
            alert('请输入用户名');
            return;
        }
        const boardData = [];
        for (let i = 0; i < BOARD_SIZE; i++) {
            const rowData = [];
            for (let j = 0; j < BOARD_SIZE; j++) {
                const cell = document.querySelector(`.cell[data-row="${i}"][data-col="${j}"]`);
                const stone = cell.querySelector('.stone');
                if (stone) {
                    rowData.push(stone.classList.contains('black') ? 1 : 2);
                } else {
                    rowData.push(0);
                }
            }
            boardData.push(rowData);
        }
        const jsonData = JSON.stringify(boardData);
        try {
            const response = await fetch('/api/wuziqi/save-game', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, boardData: jsonData })
            });
            const message = await response.text();
            if (response.ok) {
                alert(message);
            } else {
                alert(message);
            }
        } catch (error) {
            alert('保存存档时出错: ' + error.message);
        }
    }

    // 读取游戏存档
    async function loadGame() {
        const username = usernameInput.value;
        if (!username) {
            alert('请输入用户名');
            return;
        }
        try {
            const response = await fetch(`/api/wuziqi/load-game?username=${username}`, { method: 'GET' });
            if (response.ok) {
                const data = await response.json();
                if (data) {
                    const boardData = JSON.parse(data.boardData);
                    currentPlayer = data.currentPlayer;
                    drawBoard();
                    for (let i = 0; i < BOARD_SIZE; i++) {
                        for (let j = 0; j < BOARD_SIZE; j++) {
                            if (boardData[i][j] !== 0) {
                                placeStone(i, j, boardData[i][j]);
                            }
                        }
                    }
                    statusText.textContent = `当前玩家: ${currentPlayer === 1 ? '黑棋' : '白棋'}`;
                    alert('游戏存档加载成功');
                } else {
                    alert('没有可用的存档');
                }
            } else {
                alert('没有可用的存档' + response.statusText);
            }
        } catch (error) {
            alert('没有可用的存档' + error.message);
        }
    }

    // 监听新游戏按钮点击事件
    newGameButton.addEventListener('click', resetGame);
    // 监听保存存档按钮点击事件
    saveGameButton.addEventListener('click', saveGame);
    // 监听读取存档按钮点击事件
    loadGameButton.addEventListener('click', loadGame);
    drawBoard();
</script>
</body>
</html>